﻿using API_Test_KashFlow.com.securedwebapp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace API_Test_KashFlow
{
    class Program
    {
        // variaveis globais
        static KashFlowAPI kash = new KashFlowAPI();
        static string username = "luiscoisas2", password = "123456";
        static string token;

        static void Main(string[] args)
        {
            // fazer login
            string strStatus, strStatusDetail;
            bool testCred = kash.isUserVATRegistered(username, password, out strStatus, out strStatusDetail); // testar credenciais

            if (strStatus != "OK")
            {
                if (strStatusDetail.EndsWith("access list"))
                {
                    Console.WriteLine("Credentials are valid, but must enable API access.");
                }
            }
            else
            {
                Console.WriteLine("Credentials are valid!");
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }

            // imprimir menu
            int op = -1;
            GetJsonAPI getJsonAPI = new GetJsonAPI();
            
            while(op != 0){
                printMenu();
                op = int.Parse(Console.ReadLine());

                if(op == 1)
                {
                    listCustomers();
                }
                else if(op == 2)
                {
                    Console.Write("ID do cliente? ");
                    int id = int.Parse(Console.ReadLine());
                    listInvoicesByCustomer(id);
                }
                else if (op == 3)
                {
                    string customer = "luis";
                    createInvoice(customer);
                }
                else if (op == 4)
                {
                    addPayment();
                }
                else if (op == 5)
                {
                    addCustomer();
                }
                else if (op == 6)
                {
                    getJsonAPI.listarQuartos();
                }
                else if (op == 7)
                {
                    token = getJsonAPI.receberTokenRentaCar();
                    Console.WriteLine(token);
                }
                else if (op == 8)
                {
                    string startDate, endDate;
                    Console.Write("Data Início? ");
                    startDate = Console.ReadLine();
                    Console.Write("Data Fim? ");
                    endDate = Console.ReadLine();
                    getJsonAPI.listarCarrosEntreDatas(startDate, endDate);
                }
                else if (op == 9)
                {
                    int idCategoria, quantidade;
                    string dataInicio, dataFim, firstName, lastName, email, telefone;
                    Console.Write("ID da Categoria? ");
                    idCategoria = int.Parse(Console.ReadLine());
                    Console.Write("Quantidade? ");
                    quantidade = int.Parse(Console.ReadLine());
                    Console.Write("Data Início? ");
                    dataInicio = Console.ReadLine();
                    Console.Write("Data Fim? ");
                    dataFim = Console.ReadLine();
                    Console.Write("Primeiro Nome? ");
                    firstName = Console.ReadLine();
                    Console.Write("Apelido? ");
                    lastName = Console.ReadLine();
                    Console.Write("Email? ");
                    email = Console.ReadLine();
                    Console.Write("Telefone? ");
                    telefone = Console.ReadLine();
                    getJsonAPI.reservarQuarto(idCategoria, quantidade, dataInicio, dataFim, firstName, lastName, email, telefone);
                }
                else if (op == 10)
                {
                    int carID;
                    string startDate, endDate;
                    Console.Write("ID da Categoria? ");
                    carID = int.Parse(Console.ReadLine());
                    Console.Write("Data Início? ");
                    startDate = Console.ReadLine();
                    Console.Write("Data Fim? ");
                    endDate = Console.ReadLine();
                    getJsonAPI.alugarCarro(carID, startDate, endDate);
                }
            }
        }        

        // imprimir menu
        private static void printMenu()
        {
            Console.WriteLine("\n### MENU ###");
            Console.WriteLine("1 - Listar clientes");
            Console.WriteLine("2 - Listar invoices");
            Console.WriteLine("3 - Criar invoice");
            Console.WriteLine("4 - Adicionar um pagamento");
            Console.WriteLine("5 - Adicionar cliente");
            Console.WriteLine("6 - Listar Quartos");
            Console.WriteLine("7 - Receber Token Rent-a-Car (Gera novo token!)");
            Console.WriteLine("8 - Listar Carros entre Datas");
            Console.WriteLine("9 - Reservar Quarto");
            Console.WriteLine("10 - Alugar Carro");
            Console.WriteLine("0 - Sair");
            Console.Write("Opção -> ");
        }

        // adicionar um cliente
        private static void addCustomer()
        {
            Customer customer = new Customer();
            Console.Write("Customer Name: ");
            customer.Name = Console.ReadLine();

            string strStatus, strStatusDetail;
            int result = kash.InsertCustomer(username, password, customer, out strStatus, out strStatusDetail);
            Console.WriteLine(result);
        }

        // adicionar um pagamento
        private static void addPayment()
        {
            Payment payment = new Payment();
            payment.PayDate = DateTime.Today;
            payment.PayAmount = 100;
            payment.PayNote = "Pago na totalidade";
            payment.PayInvoice = 1; // especificar o número do invoice (não o ID dele)

            string strStatus, strStatusDetail;
            int result = kash.InsertInvoicePayment(username, password, payment, out strStatus, out strStatusDetail);
            Console.WriteLine(result);
        }

        // criar um invoice
        private static void createInvoice(string customer)
        {
            Invoice invoice = new Invoice();
            invoice.CustomerName = customer;
            invoice.CustomerID = 15015991; // sempre especificar ID do cliente
            invoice.InvoiceDate = DateTime.Today;
            //Console.WriteLine("Due Date:");
            //Console.Write("\tDay: ");
            //Int32 day = Int32.Parse(Console.ReadLine());
            //Console.Write("\tMonth: ");
            //Int32 month = Int32.Parse(Console.ReadLine());
            //Console.Write("\tYear: ");
            //Int32 year = Int32.Parse(Console.ReadLine());
            //invoice.DueDate = new System.DateTime(year,month,day);
            invoice.CurrencyCode = "€";
            InvoiceLine invline1 = new InvoiceLine();
            Console.Write("\nDescription: ");
            invline1.Description = Console.ReadLine();
            Console.Write("\nQuantity: ");
            invline1.Quantity = int.Parse(Console.ReadLine());
            Console.Write("\nRate: ");
            invline1.Rate = int.Parse(Console.ReadLine());
            invoice.Lines = new object[]{invline1};

            string strStatus, strStatusDetail;
            int result = kash.InsertInvoice(username, password, invoice, out strStatus, out strStatusDetail);
            Console.WriteLine(result);
        }

        // listar invoices por ID do cliente
        public static void listInvoicesByCustomer(int customerID)
        {
            string strStatus, strStatusDetail;
            Invoice[] invoices = kash.GetInvoicesForCustomer(username, password, customerID, out strStatus, out strStatusDetail);
            for (int i = 0; i < invoices.Length; i++)
            {
                Console.WriteLine("\n$$$ ITEM " + (i + 1) + " $$$");
                Console.WriteLine("Amount Paid: "+invoices[i].AmountPaid);
                Console.WriteLine("Currency Code: " + invoices[i].CurrencyCode);
                Console.WriteLine("Customer: " + invoices[i].Customer);
                Console.WriteLine("Customer ID: " + invoices[i].CustomerID);
                Console.WriteLine("Customer Name: " + invoices[i].CustomerName);
                Console.WriteLine("Customer Reference: " + invoices[i].CustomerReference);
                Console.WriteLine("Delivery Address: " + invoices[i].DeliveryAddress);
                Console.WriteLine("Due Date: " + invoices[i].DueDate);
                Console.WriteLine("Estimate Category: " + invoices[i].EstimateCategory);
                Console.WriteLine("Exchange Rate: " + invoices[i].ExchangeRate);
                Console.WriteLine("Invoice Date: " + invoices[i].InvoiceDate.ToString("d"));
                Console.WriteLine("Invoice DB ID: " + invoices[i].InvoiceDBID);
                Console.WriteLine("Invoice Number: " + invoices[i].InvoiceNumber);   
                for (int j = 0; j < invoices[i].Lines.Length; j++)
                {
                    Console.WriteLine("Item " + (j + 1) + " :");
                    InvoiceLine invline = (InvoiceLine) invoices[i].Lines[j];
                    Console.WriteLine("\tDescription: "+invline.Description);
                    Console.WriteLine("\tQuantity: "+invline.Quantity);
                    Console.WriteLine("\tRate: "+invline.Rate);
                }
                Console.WriteLine("Net Amount: " + invoices[i].NetAmount);
                Console.WriteLine("Paid: " + invoices[i].Paid);
                Console.WriteLine("Perma Link: " + invoices[i].PermaLink);
                Console.WriteLine("Project ID: " + invoices[i].ProjectID);
                Console.WriteLine("Readable String: " + invoices[i].ReadableString);
                Console.WriteLine("Suppress Total: " + invoices[i].SuppressTotal);
                Console.WriteLine("Use Custom Delivery Address: " + invoices[i].UseCustomDeliveryAddress);
                Console.WriteLine("VAT Amount: " + invoices[i].VATAmount);
            }
        }

        // listar clientes
        public static void listCustomers()
        {
            string strStatus, strStatusDetail;
            Customer[] customers = kash.GetCustomers(username, password, out strStatus, out strStatusDetail);
            Console.Write("ID\t  Nome\n");
            for (int i = 0; i < customers.Length; i++)
            {
                // imprime informação do cliente
                Console.Write(customers[i].CustomerID+"  ");
                Console.Write(customers[i].Name+"\n");
            }
        }
    }
}
